﻿<!DOCTYPE html>
<head>
    <meta charset="UTF-8">

    <script type="text/javascript">

        var pc;

		function start(remoteOffer) {

            if (remoteOffer === '') {
                return alert('The SDP offer cannot not be empty.');
            }

			let videoControl = document.querySelector('#videoCtl');
			
			pc = new RTCPeerConnection(null);

            pc.ontrack = ({ track, streams: [stream] }) => {
                track.onunmute = () => {
                    videoControl.srcObject = stream;
                };
            };

            pc.onicegatheringstatechange = function () {
                console.log("onicegatheringstatechange: " + pc.iceGatheringState);
            }

            pc.oniceconnectionstatechange = function () {
                console.log("oniceconnectionstatechange: " + pc.iceConnectionState);
            }

            pc.onsignalingstatechange = function () {
                console.log("onsignalingstatechange: " + pc.signalingState);
            }

            pc.onicecandidate = function (event) {
                if (event.candidate) {
                    console.log('new-ice-candidate:');
                    console.log(event.candidate.candidate);
                    console.log(event.candidate);
                }
            };

            pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(remoteOffer))))

            //const offer = await pc.createOffer();
            //document.getElementById('localSessionDescription').value = btoa(JSON.stringify(pc.localDescription))

			//pc.setRemoteDescription(new RTCSessionDescription({ type: "offer", sdp: offerSDP }));

			//// Create the answer SDP.
			pc.createAnswer().then(function (answer) {
				console.log("answer SDP: " + answer.sdp)
                pc.setLocalDescription(answer);
                document.getElementById('localAnswer').value = btoa(JSON.stringify(pc.localDescription))
			});	
		};	

        function closePeer() {
            if (pc != null) {
                console.log("close peer");
                pc.close();
            }
        };

    </script>
</head>
<body>

    <video controls autoplay="autoplay" id="videoCtl" width="640" height="480"></video>

    <h3>Paste in Remote SDP Offer (as a base64 string)</h3>
    <textarea id="remoteOffer" rows="10" cols="80"></textarea> <br />
    <button type="button" class="btn btn-success" onclick="start(document.getElementById('remoteOffer').value);">Start</button>

    <h3>Local SDP Answer will appear here (as a base64 string)</h3>
    <textarea id="localAnswer" readonly="true" rows="10" cols="80"></textarea> <br />

    <button type="button" class="btn btn-success" onclick="closePeer();">Close</button>

</body>
